package Service;

import entity.WorkOrder;
import org.springframework.stereotype.Service;
import mapper.WorkOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

@Service
public class WorkOrderService {

    @Autowired
    private WorkOrderMapper workOrderMapper;

    public void addWorkOrder(WorkOrder workOrder) {
        workOrderMapper.insert(workOrder);
    }

    //回单
    public void replyWorkOrder(WorkOrder workOrder) {
        if (workOrder.getId() == null) {
            throw new IllegalArgumentException("工单ID不能为空");
        }
        if (workOrder.getReplyContent() == null || workOrder.getReplyContent().isEmpty()) {
            throw new IllegalArgumentException("回单内容不能为空");
        }
        if (workOrder.getHandlerId() == null) {
            throw new IllegalArgumentException("处理人ID不能为空");
        }

        WorkOrder dbWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        if (dbWorkOrder == null) {
            throw new RuntimeException("工单不存在");
        }
        if (dbWorkOrder.getStatus() != 0) {
            throw new RuntimeException("工单状态异常，当前状态：" + dbWorkOrder.getStatus());
        }
        int rows = workOrderMapper.replyWorkOrder(workOrder);
        if (rows == 0) {
            throw new RuntimeException("回单失败，工单状态已变更");
        }
        workOrderMapper.replyWorkOrder(workOrder);
    }

    //退单
    public void cancelWorkOrder(WorkOrder workOrder) {
        if (workOrder.getId() == null) {
            throw new IllegalArgumentException("工单ID不能为空");
        }
        if (workOrder.getCancelReason() == null || workOrder.getCancelReason().trim().isEmpty()) {
            throw new IllegalArgumentException("退单原因不能为空");
        }
        if (workOrder.getCancelOperator() == null) {
            throw new IllegalArgumentException("退单人ID不能为空");
        }
        WorkOrder dbWorkOrder = workOrderMapper.selectWorkOrderById(workOrder.getId());
        if (dbWorkOrder == null) {
            throw new RuntimeException("工单不存在：" + workOrder.getId());
        }
        if (!Objects.equals(dbWorkOrder.getStatus(), 0)) {
            throw new RuntimeException("工单状态异常，当前状态：" + dbWorkOrder.getStatus());
        }

        int affectedRows = workOrderMapper.cancelWorkOrder(workOrder);
        if (affectedRows == 0) {
            throw new RuntimeException("退单失败，工单状态已变更");
        }
        workOrderMapper.cancelWorkOrder(workOrder);
    }
}
